<style lang="stylus" type="text/stylus">
  @import 'unitChart.styl';
</style>

<template>
  <div class="all-group">
    <div v-if="answers.length && problemItem.problems.length"
         class="answers-group" v-for="(problemItem,problemIndex) in answers">
      <div class="all-group-item"
           v-for="(problems,unitChildIndex) in problemItem.problems"
           :key="problemIndex">
        <div class="unit-item" :key="unitChildIndex">

          <div :id="problems.position"
               class="unit-item-card card-com">
            <div class="card-con-com first-card">
              <div class="left">
                <Input class="unit-description" v-model="problems.title" type="textarea" :autosize="true"
                       placeholder="请填写问题描述"/>
                <ButtonGroup class="unit-tools">
                  <Button icon="chevron-up" :disabled="unitChildIndex==0"
                          @click="unitDownUp(problemIndex,unitChildIndex,true)"></Button>
                  <Button icon="chevron-down" :disabled="unitChildIndex==problemItem.problems.length-1"
                          @click="unitDownUp(problemIndex,unitChildIndex)"></Button>
                  <Button @click="unUnit(problemIndex,unitChildIndex)" class="untied"><i
                    class="iconfont icon-unbind_1"></i></Button>
                  <Button @click="delUnit(problemIndex,unitChildIndex)" class="del" icon="android-close"></Button>
                </ButtonGroup>
              </div>
              <div class="right">
                <ul class="unit-problem-list">
                  <li v-for="(child,childIndex) in problems.answers"
                      :id="child.position"
                      :key="childIndex"
                      :draggable='draggableActive'
                      @dragstart='unitiDrag($event,problemIndex, unitChildIndex, childIndex)'
                      @drop='unitiDrop($event,problemIndex,unitChildIndex,childIndex)'
                      @dragover='unitiAllowDrop'
                      class="unit-problem-list-li">
                    <Input placeholder="无" v-model="child.content">
                    <Poptip :transfer="true" slot="append" placement="right" width="313">
                      <Button type="ghost">{{child.problems?child.problems.length:0}}</Button>
                      <div class="unit-policy-prizes" slot="content">
                        <VuePerfectScrollbar class="unit-policy-prizes-ps">
                          <div class="policy-prize-item"
                               :key="policyPrizeIndex"
                               v-for="(policyPrize,policyPrizeIndex) in child.prizes">
                            <p class="policy-title">政策：{{policyPrize.shortTitle}}</p>
                            <ul>
                              <li v-for="(prizes,prizesIndex) of policyPrize.prizes"
                                  :key="prizesIndex"
                                  class="prize-item">
                                <span class="prize">资助：{{prizes.title}}</span>
                                <span
                                  @click="delPrize(problems.position,child.position,child.prizes,policyPrizeIndex,policyPrize.prizes,prizesIndex)"
                                  class="del-prize"><i
                                  class="iconfont icon-close"></i></span>
                              </li>
                            </ul>
                          </div>
                        </VuePerfectScrollbar>
                        <div class="policy-prize-drag">
                          <span :draggable="true"
                                @mouseenter="chartToPolicySeen(child.prizes)"
                                @mouseleave="chartToPolicyLeave(child.prizes)"
                                @dragstart="chartToPolicyFun($event,problemIndex,unitChildIndex,childIndex)"
                                class="drag"><i class="iconfont icon-line_1"></i></span>
                        </div>
                      </div>
                    </Poptip>
                    </Input>
                    <div class="problem-child-tools">
                      <ButtonGroup>
                        <Button draggable='true'
                                @dragstart="draggableActive=!0"
                                @dragover="draggableActive=false"
                                class="drag"><i class="iconfont icon-shangxia"></i></Button>
                        <Button icon="android-add"
                                @click="addUnitChild(problemIndex,unitChildIndex,childIndex)"></Button>
                        <Button draggable='true'
                                @dragstart="mouseAnswers"
                                @dragover="draggableActive=false"
                                class="move">
                          <div @mouseenter="chartToUnitedSeen(child)"
                               @mouseleave="chartToUnitedLeave(child)"><i class="iconfont icon-line_1"></i></div>
                        </Button>
                        <Button class="del" @click="delUnitChild(problemIndex,unitChildIndex,childIndex)"
                                icon="android-close"></Button>
                      </ButtonGroup>
                    </div>
                  </li>
                </ul>
                <span class="btn-add" @click="addProblemChild(problemIndex,unitChildIndex)"><Icon
                  type="android-add"></Icon></span>
              </div>
              <div class="clearfix"></div>
              <div class="btn-add-up btn-add-com">
                <span class="btn-add" @click="addUnit(problemIndex,unitChildIndex,true)"><Icon
                  type="android-add"></Icon></span>
              </div>
              <div class="btn-add-down btn-add-com">
                <span class="btn-add" @click="addUnit(problemIndex,unitChildIndex)"><Icon
                  type="android-add"></Icon></span>
              </div>
            </div>
          </div>
          <unitChart v-if="hasProblem(problems)"
                     :unitObj="problems"
                     :dragUnUnitObj="dragUnUnitObj"
                     :chartToPolicy="chartToPolicy"
                     :policyToChart="policyToChart"
                     :delChartPrize="delChartPrize"
                     @pointLine="pointLine"
                     @changeUnUnitData="changeUnUnitData"
                     @changeChartToPolicy="changeChartToPolicy"
                     @changePolicyToChart="changePolicyToChart"
                     @chartToUnUnitFun="chartToUnUnitFun"
                     @delPolicyPrizeFun="delPolicyPrizeFun"
                     @unUnitItem="unUnitItem"></unitChart>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">

  export default {
    name      : "unitChart",
    data() {
      return {
        draggableActive: false
      };
    },
    props     : [
      "unitObj",
      "dragUnUnitObj",
      "chartToPolicy",
      "policyToChart",
      "delChartPrize"
    ],
    computed  : {
      answers() {
        return this.unitObj.answers;
      }
    },
    methods   : {
      hasProblem(data) {
        return data.answers.find(v => {
          return v.problems && v.problems.length;
        });
      },
      getUnitChild(...arr) {
        if (arr.length == 3) {
          return this.unitObj.answers[arr[0]].problems[arr[1]].answers[arr[2]];
        } else {
          return this.unitObj.answers[arr[0]].problems[arr[1]];
        }
      },
      unitiDrag(event, ...arr) {
        event.dataTransfer.setData("Text", arr[2]);
        this.changeUnUnitData();
        this.changePolicyToChart();
        event.toElement.className.match(/move/g)
          ? this.chartToUnUnitFun(this.getUnitChild(...arr))
          : "";
      },
      unitiDrop(e, ...arr) {
        this.unitiAllowDrop(e);
        if (!this.dragUnUnitObj.obj && !this.policyToChart) {
          let $arr      = this.getUnitChild(arr[0], arr[1]).answers.concat([]),
              dragIndex = e.dataTransfer.getData("Text"),
              temp      = $arr.splice(dragIndex, 1);
          $arr.splice(arr[2], 0, temp[0]);
          this.getUnitChild(arr[0], arr[1]).answers = $arr;
          setTimeout(() => {
            this.lineOfPoint();
          }, 50);
        } else if (this.dragUnUnitObj.obj) {
          this.dragUnUnitObj.obj.position = `${this.getUnitChild(...arr).position}_${(Math.random() * Date.now()).toFixed(0)}`
          this.getUnitChild(...arr).problems.push(this.dragUnUnitObj.obj)
          this.changeUnUnitData({index: this.dragUnUnitObj.index});
          setTimeout(() => {
            this.lineOfPoint();
          }, 50);
        } else if (this.policyToChart) {
          let chartProblem = this.getUnitChild(arr[0], arr[1]);
          let chartAnswers = this.getUnitChild(...arr);
          let chartPrizes  = chartAnswers.prizes;
          let policy       = chartPrizes.find(v => {
            return v.policyId == this.policyToChart.policy.id;
          });
          let prize        = policy
            ? policy.prizes.find(v => {
              return v.prizeId == this.policyToChart.prize.id;
            })
            : "";
          if (!policy) {
            chartPrizes.push({
              policyId  : this.policyToChart.policy.id,
              shortTitle: this.policyToChart.policy.shortTitle,
              prizes    : [
                {
                  prizeId: this.policyToChart.prize.id,
                  title  : this.policyToChart.prize.title
                }
              ]
            });
          }
          if (policy && !prize) {
            policy.prizes.push({
              prizeId: this.policyToChart.prize.id,
              title  : this.policyToChart.prize.title
            });
            setTimeout(() => {
              this.lineOfPoint();
            }, 50);
          }

          let hasProblem = this.policyToChart.prize.dataCache.find(v => {
            return v.position == chartProblem.position;
          });
          let policyItem = hasProblem
            ? hasProblem.answers.find(v => {
              return v.position == chartAnswers.position;
            })
            : "";

          if (!hasProblem) {
            this.policyToChart.prize.dataCache.push({
              title   : chartProblem.title,
              id      : chartProblem.id,
              position: chartProblem.position,
              answers : [
                {
                  id      : chartAnswers.id,
                  position: chartAnswers.position,
                  content : chartAnswers.content
                }
              ]
            });
            setTimeout(() => {
              this.lineOfPoint();
            }, 50);
          } else if (hasProblem && !policyItem) {
            hasProblem.answers.push({
              id      : chartAnswers.id,
              position: chartAnswers.position,
              content : chartAnswers.content
            });
            setTimeout(() => {
              this.lineOfPoint();
            }, 50);
          }

          this.changePolicyToChart();
        }
      },
      unitiAllowDrop(event) {
        event.preventDefault();
      },
      changeUnUnitData(index) {
        this.$emit("changeUnUnitData", index);
      },
      addProblemChild(problemIndex, unitChildIndex) {
        let id = (Math.random() * Date.now()).toFixed(0);
        this.getUnitChild(problemIndex, unitChildIndex).answers.push({
          position: `unit_${id}`,
          content : "",
          prizes  : [],
          problems: []
        });
        setTimeout(() => {
          this.lineOfPoint();
        }, 50);
      },
      addUnitChild(...arr) {
        this.getUnitChild(...arr).problems.push({
          position: `${this.getUnitChild(...arr).position}_${(Math.random() *
            Date.now()
          ).toFixed(0)}`,
          title   : "",
          answers : []
        });
        setTimeout(() => {
          this.lineOfPoint();
        }, 50);
      },
      delUnitChild(...arr) {
        let problems = this.getUnitChild(arr[0], arr[1]),
            answer   = this.getUnitChild(...arr);
        for (let v of answer.prizes) {
          for (let p of v.prizes) {
            this.delPolicyPrizeFun({
              policyId       : v.policyId,
              prizeId        : p.prizeId,
              problemPosition: problems.position,
              answerPosition : answer.position
            });
          }
        }
        for (let v of answer.problems) {
          this.delChildPrizesFun(v);
        }

        this.getUnitChild(arr[0], arr[1]).answers.splice(arr[2], 1);
        setTimeout(() => {
          this.lineOfPoint();
        }, 50);
      },
      addUnit(problemIndex, unitChildIndex, up) {
        const positionId = this.unitObj.answers[problemIndex].position;
        const unit       = {
          position: `${positionId ? positionId : "first"}_${(Math.random() *
            Date.now()
          ).toFixed(0)}`,
          title   : "",
          answers : []
        };
        if (up) {
          this.unitObj.answers[problemIndex].problems.splice(
            unitChildIndex,
            0,
            unit
          );
          setTimeout(() => {
            this.lineOfPoint();
          }, 50);
        } else {
          this.unitObj.answers[problemIndex].problems.splice(
            unitChildIndex + 1,
            0,
            unit
          );
          setTimeout(() => {
            this.lineOfPoint();
          }, 50);
        }
      },
      delChildPrizesFun(data) {
        if (!data.answers.length) {
          return;
        }
        for (let v of data.answers) {
          if (v.prizes.length) {
            for (let prize of v.prizes) {
              for (let p of prize.prizes) {
                this.delPolicyPrizeFun({
                  policyId       : prize.policyId,
                  prizeId        : p.prizeId,
                  problemPosition: data.position,
                  answerPosition : v.position
                });
              }
            }
          }
          if (v.problems && v.problems.length) {
            for (let problem of v.problems) {
              this.delChildPrizesFun(problem);
            }
          }
        }
      },
      delUnit(problemIndex, unitChildIndex) {
        this.delChildPrizesFun(
          this.unitObj.answers[problemIndex].problems[unitChildIndex]
        );
        this.unitObj.answers[problemIndex].problems.splice(unitChildIndex, 1);
        setTimeout(() => {
          this.lineOfPoint();
        }, 50);
      },
      unUnitFn(arr, answers) {
        if (!answers.problems.length) {
          return;
        }
        for (let z of answers.problems) {
          let answers = z.answers;
          arr.push(z);
          for (let v of answers) {
            this.unUnitFn(arr, v);
          }
        }
      },
      unUnit(problemIndex, unitChildIndex) {
        const unUnitObj = this.getUnitChild(problemIndex, unitChildIndex);
        let arr         = [];
        this.unitObj.answers[problemIndex].problems.splice(unitChildIndex, 1);
        arr.push(unUnitObj);
        for (let v of unUnitObj.answers) {
          this.unUnitFn(arr, v);
        }
        for (let v of arr) {
          this.delChildPrizesFun(v);
        }
        for (let v of arr) {
          for (let z of v.answers) {
            z.problems = [];
            z.prizes   = [];
          }
        }

        this.unUnitItem(arr);
        setTimeout(() => {
          this.lineOfPoint();
        }, 50);
      },
      unUnitItem(item) {
        this.$emit("unUnitItem", item);
      },
      swapItems(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0];
        return arr;
      },
      unitDownUp(problemIndex, unitChildIndex, up) {
        let arr = this.unitObj.answers[problemIndex].problems;
        if (up) {
          if (arr.length > 1 && unitChildIndex != 0) {
            let x = unitChildIndex,
                y = unitChildIndex - 1;
            this.swapItems(arr, x, y);
            setTimeout(() => {
              this.lineOfPoint();
            }, 50);
          }
        } else {
          if (arr.length > 1 && unitChildIndex != arr.length - 1) {
            let x = unitChildIndex + 1,
                y = unitChildIndex;
            this.swapItems(arr, x, y);
            setTimeout(() => {
              this.lineOfPoint();
            }, 50);
          }
        }
      },
      chartToUnUnitFun(item) {
        this.$emit("chartToUnUnitFun", item);
      },
      chartToPolicyFun(e, ...arr) {
        this.changeChartToPolicy({
          problem: this.getUnitChild(arr[0], arr[1]),
          answers: this.getUnitChild(...arr)
        });
        for (let v of document.querySelectorAll(".funfListLi")) {
          v.className = "funfListLi selected";
        }
      },
      chartToPolicyDrag(e) {
      },
      changeChartToPolicy(data) {
        this.$emit("changeChartToPolicy", data);
      },
      changePolicyToChart(data) {
        this.$emit("changePolicyToChart", data);
      },
      delPrize(problemPosition,
               answerPosition,
               childPrizes,
               policyPrizeIndex,
               policyPrizePrizes,
               prizesIndex) {
        this.delPolicyPrizeFun({
          policyId       : childPrizes[policyPrizeIndex].policyId,
          prizeId        : policyPrizePrizes[prizesIndex].prizeId,
          problemPosition: problemPosition,
          answerPosition : answerPosition
        });
        policyPrizePrizes.splice(prizesIndex, 1);
        if (!policyPrizePrizes.length) {
          childPrizes.splice(policyPrizeIndex, 1);
        }
      },
      delPolicyPrizeFun(data) {
        this.$emit("delPolicyPrizeFun", data);
      },
      chartToPolicySeen(prizes) {
        for (let v of document.querySelectorAll(".funfListLi")) {
          v.className = "funfListLi selected";
        }
      },
      chartToPolicyLeave() {
        for (let v of document.querySelectorAll(".funfListLi")) {
          v.className = "funfListLi";
        }
      },
      mouseAnswers() {
        this.draggableActive = !0;
        this.chartToUnitedSeen();
      },
      chartToUnitedSeen(sel) {
        const united = document.querySelector(".SidebarRight"),
              card   = united.querySelectorAll(".card-con-com");
        for (let v of card) {
          v.className = "card-con-com selected";
        }
      },
      chartToUnitedLeave() {
        const united = document.querySelector(".SidebarRight"),
              card   = united.querySelectorAll(".card-con-com");
        for (let v of card) {
          v.className = "card-con-com";
        }
      },
      pointLine() {
        this.$emit("pointLine", {});
      },
      lineOfPoint() {
        this.$emit("pointLine", {});
      }
    },
    mounted() {},
    created() {},
    watch     : {
      delChartPrize: function (res) {
        const problemPosition = res.problem.position,
              answerPosition  = res.answer.position;
        let problemItem, answerItem;
        for (let v of this.unitObj.answers) {
          if (v.problems) {
            for (let j of v.problems) {
              if (j.position == problemPosition) {
                problemItem = j;
              }
            }
          }
        }
        answerItem = problemItem
          ? problemItem.answers.find(v => {
            return v.position == answerPosition;
          })
          : "";
        if (answerItem) {
          let policy      = answerItem.prizes.find(v => {
            return v.policyId == res.policyId;
          });
          let policyIndex = answerItem.prizes.findIndex(v => {
            return v.policyId == res.policyId;
          });
          let prizeIndex  = policy.prizes.findIndex(v => {
            return v.prizeId == res.prizeId;
          });
          policy.prizes.splice(prizeIndex, 1);
          !policy.prizes.length ? answerItem.prizes.splice(policyIndex, 1) : "";
        }
      }
    }
  };
</script>
